//
//  DMQRCodeCIDetector.swift
//  SwiftText
//
//  Created by Maker on 2022/3/11.
//

import UIKit

class DMQRCodeCIDetector {
    
    class public func detectImage(image: UIImage) -> [DMScanResult]? {
        if image.size.width < 5  {return nil}
        if let imageData = image.jpegData(compressionQuality: 0.5) {
            if let cicImage = CIImage(data: imageData) {
                return detectCIImage(image: cicImage, size: image.size)
            }
        }
       return nil
    }
    
    class private func detectCIImage(image: CIImage, size: CGSize) -> [DMScanResult]? {
        let detector:CIDetector = {
            let content = CIContext()
            let param = [CIDetectorAccuracy : CIDetectorAccuracyLow]
            return CIDetector(ofType: CIDetectorTypeQRCode, context: content, options: param) ?? CIDetector()
        }()
        let features:[CIFeature] = detector.features(in: image)
        var tempArray = [DMScanResult]()
        for fetture in features {
            if let qrFetture = fetture as? CIQRCodeFeature {
                tempArray.append(DMScanResult(content: qrFetture.messageString ?? "", rect: .zero))
            }
        }
        return (tempArray.count != 0) ? tempArray : nil
    }
}
